<?php

namespace App\Http\Controllers\Api;

use App\Models\Manager;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;

class ManagerController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $per_page = $request->get('per_page', 10);
        $current_page = $request->get('current_page', 1);
        return Manager::query()->with('roles')->forPage($current_page)->paginate($per_page);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $roles = $request->get('roles');
        $name = $request->get('name');
        $email = $request->get('email');
        $password = $request->get('password');
        $avatar = $request->get('avatar');
        $user = Manager::create(['name' => $name, 'email' => $email,'avatar'=>$avatar, 'password' => Hash::make($password)]);
        $user->assignRole(json_decode($roles));
        return $user;
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        return Manager::query()->with('roles')->find($id);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $user = Manager::query()->find($id);
        $roles = $request->get('roles');
        $name = $request->get('name');
        $email = $request->get('email');
        $password = $request->get('password', '');
        $avatar = $request->get('avatar');
        $attrs = ['name' => $name, 'email' => $email,'avatar'=>$avatar];
        if ($password) {
            array_push($attrs,'password',Hash::make($password));
        }
        $user->update($attrs);
        $user->syncRoles(json_decode($roles));
        return $user;
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
